package com.ftg.supermarket.comm;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 布衣
 */
public class JwtComm {

    private static final String SECRET = "kjxkjx";

    /**
     * 生成token
     *
     * @param claims 负载
     * @return jwt串
     */
    public static String createToken(Map<String, Object> claims) {
        //是哪天创建的
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() * 3600 * 1000))
                .signWith(SignatureAlgorithm.HS512, Md5Me.getMD5(SECRET)).compact();
    }

    /**
     * 验证token信息
     *
     * @param token 令牌
     */
    public static JwtInfo verifyToken(String token) {
        if (null == token || token.isEmpty()) {
            return new JwtInfo(false, "请传入令牌", null);
        }
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(Md5Me.getMD5(SECRET)).parseClaimsJws(token);
            return new JwtInfo(true, "验证成功", claimsJws.getBody());
        } catch (ExpiredJwtException e) {
            return new JwtInfo(false, "令牌已过期", null);
        } catch (UnsupportedJwtException uj) {
            return new JwtInfo(false, "请正确传递jwt令牌", null);
        } catch (SignatureException s) {
            return new JwtInfo(false, "令牌签名错误", null);
        } catch (IllegalArgumentException i) {
            return new JwtInfo(false, "令牌参数错误", null);
        }
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", "kjx");
        map.put("id", 123);
        //创建令牌
        String token = createToken(map);
        System.out.println(token);

        String a = token;
        JwtInfo jwtInfo = verifyToken(a);
        System.out.println(jwtInfo);
    }

}
